// pages/creationwzh/creationwzh.js
const app = getApp()
Page({
  data: {
    coverImageUrl: '', // 封面图片URL
    title: '', // 推荐帖标题
    content: '', // 推荐帖内容
    showSuccessModal: false, // 成功提示模态框显示状态
    rec: null,
    flag: 0
  },

  // 返回上一页
  onClickLeft() {
    // 重置表单
    this.setData({
      title: '',
      content: '',
      coverImageUrl: ''
    });
    console.log(this.data.title);

    // 清空编辑器内容
    if (this.editorCtx) {
      this.editorCtx.setContents({
        html: ''
      });
    }
    wx.navigateBack()
  },

  // 选择封面图片并上传
  chooseCoverImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'], // 优先使用压缩图
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0];
        const imageUrl = await this.uploadImage(tempFilePath);
        if (imageUrl) {
          this.setData({
            coverImageUrl: imageUrl
          });
        }
      },
      fail: (err) => {
        console.error('选择图片失败:', err);
      }
    })
  },

  // 图片上传接口
  uploadImage(tempFilePath) {
    const that = this;
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: 'http://localhost:8080/common/upload', // 你的上传接口
        method: 'POST',
        filePath: tempFilePath,
        name: 'file',
        formData: {
          type: 'cover' // 上传类型标识
        },
        header: {
          Authorization: app.globalData.token
        },
        // 上传进度监听
        onProgressUpdate: (res) => {
          const progress = Math.round((res.loaded / res.total) * 100);
          that.setData({
            uploadProgress: progress
          });
          console.log(`上传进度: ${progress}%`);
        },
        success: (uploadRes) => {
          try {
            const result = JSON.parse(uploadRes.data);
            if (result.code === 200) {
              if (result.url) {
                that.setData({
                  uploadProgress: 0
                });
                resolve(result.url);
              } else {
                wx.showToast({
                  title: '上传成功，但未获取到图片URL',
                  icon: 'none',
                  duration: 2000
                });
                reject(new Error('未获取到图片URL'));
              }
            } else {
              wx.showToast({
                title: `上传失败: ${result.msg}`,
                icon: 'none',
                duration: 2000
              });
              reject(new Error(result.msg));
            }
          } catch (error) {
            wx.showToast({
              title: '解析服务器响应数据失败',
              icon: 'none',
              duration: 2000
            });
            reject(error);
          }
        },
        fail: (err) => {
          wx.showToast({
            title: '图片上传失败',
            icon: 'none',
            duration: 2000
          });
          reject(err);
        }
      });
    });
  },

  // 删除封面图片
  removeCoverImage() {
    this.setData({
      coverImageUrl: ''
    })
  },

  // 标题输入事件
  onTitleInput(e) {
    this.setData({
      title: e.detail.value
    })
  },

  // 内容输入事件
  onContentInput(e) {
    this.setData({
      content: e.detail.html || e.detail.text
    })
  },

  // 编辑器初始化完成
  // onEditorReady() {
  //   this.createSelectorQuery().select('.rich-text-editor').context((res) => {
  //     this.editorCtx = res.context
  //   }).exec()
  // },
  // 编辑器初始化完成（关键修正）
  onEditorReady() {
    // 获取编辑器实例
    const editor = this.selectComponent('#editor');
    if (editor) {
      // 确保编辑器实例存在后再调用 setContents 方法
      editor.setContents({
        html: this.data.content
      });
    } else {
      console.error('未能获取到编辑器实例');
    }
  },

  // 格式化文本
  formatText(e) {
    const {
      name
    } = e.currentTarget.dataset;
    if (this.editorCtx) {
      this.editorCtx.format(name, '');
    }
  },

  // 插入图片（带上传功能）
  insertImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0];
        const imageUrl = await this.uploadImage(tempFilePath);
        if (imageUrl && this.editorCtx) {
          this.editorCtx.insertImage({
            src: imageUrl,
            data: {
              id: 'image_' + Date.now(),
              alt: '推荐帖图片'
            },
            width: '80%',
            success: () => {
              console.log('图片插入成功');
            }
          });
        }
      }
    })
  },

  // 发布推荐帖
  publishPost() {
    const {
      title,
      content,
      coverImageUrl
    } = this.data;

    // 表单验证
    if (!title.trim()) {
      wx.showToast({
        title: '请输入推荐帖标题',
        icon: 'none'
      });
      return;
    }

    if (!coverImageUrl) {
      wx.showToast({
        title: '请上传推荐帖封面',
        icon: 'none'
      });
      return;
    }

    if (!content.trim()) {
      wx.showToast({
        title: '请输入推荐帖内容',
        icon: 'none'
      });
      return;
    }

    if (this.data.flag === 0) {
      wx.request({
        url: 'http://localhost:8080/system/recommend',
        method: "POST",
        header: {
          Authorization: app.globalData.token,
        },
        data: {
          userId: app.globalData.userInfo.userId,
          recCover: this.data.coverImageUrl,
          recTitle: this.data.title,
          recContent: this.data.content,
          recTime: new Date()
        },
        success: (res) => {
          console.log(res);
          if (res.data.code == 200) {
            // 显示加载提示
            wx.showLoading({
              title: '发布中...',
              mask: true
            });

            // 模拟发布请求
            setTimeout(() => {
              // 隐藏加载提示
              wx.hideLoading();
              console.log(this.data.content);
              console.log(this.data.coverImageUrl);
              // 显示成功提示
              this.setData({
                showSuccessModal: true
              });

              // 重置表单
              this.setData({
                title: '',
                content: '',
                coverImageUrl: ''
              });
              console.log(this.data.title);

              // 清空编辑器内容
              if (this.editorCtx) {
                this.editorCtx.setContents({
                  html: ''
                });
              }
            }, 1500);
          }
        }
      })
    } else {
      // wx.request({
      //   url: 'http://localhost:8080/',
      // })
    }

  },

  // 关闭成功提示模态框
  onCloseSuccessModal() {
    this.setData({
      showSuccessModal: false
    });
  },

  onShow() {
    if (wx.getStorageSync('rec')) {
      this.setData({
        rec: wx.getStorageSync('rec')
      })
      wx.removeStorage({
        key: 'rec',
      })
      console.log(this.data.rec);
      this.setData({
        coverImageUrl: this.data.rec.recCover, // 封面图片URL
        title: this.data.rec.recTitle, // 推荐帖标题
        content: this.data.rec.recContent, // 推荐帖内容
        flag: 1
      })
      console.log(this.data.rec.recTitle);
      console.log(this.data.rec.recContent);
    } else {
      this.setData({
        flag: 0
      })
    }
  }
});